package com.yljk.homedoctor.view.ui;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.yljk.homedoctor.R;
import com.yljk.homedoctor.model.entity.MediaEntity;
import com.yljk.servicemanager.constants.RouterApi;
import com.yljk.servicemanager.oldbase.ModuleBaseActivity;

import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import crossoverone.statuslib.StatusUtil;

@Route(path= RouterApi.MediaPlayerActivity)
public class MediaPlayerActivity extends ModuleBaseActivity {

    private SeekBar seekBar;

    private AudioManager audioManager;

    private Timer timer;

    private ImageView mediaStateIv;
    private TextView currentTv, totalTv;
    private TextView mediaTitleTv, mediaTimeTv;
    private TextView mediaContext;
    private ImageView mediaNoImg;
    private ImageView backIv;
    private FrameLayout mediaAddLayout, mediaReduceLayout;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private boolean isSeekBarChanging;//互斥变量，防止进度条与定时器冲突。
    SimpleDateFormat format;

    private MediaEntity mediaEntity;
    private ScrollView scrollView;

    @Override
    public int bondLayout() {
        return R.layout.activity_media;
    }

    @Override
    public void initView() {
        StatusUtil.setSystemStatus(this, false, true);
        StatusUtil.setUseStatusBarColor( this,getResources().getColor(R.color.white));
        mediaAddLayout = findViewById(R.id.media_add);
        backIv = findViewById(R.id.back_iv);
        scrollView = findViewById(R.id.scrollView);
        mediaReduceLayout = findViewById(R.id.media_reduce);
        mediaContext = findViewById(R.id.media_context);
        currentTv = findViewById(R.id.current);
        totalTv = findViewById(R.id.total);
        mediaNoImg = findViewById(R.id.media_no_img);
        mediaTitleTv = findViewById(R.id.media_title);
        mediaTimeTv = findViewById(R.id.media_time);
        mediaStateIv = findViewById(R.id.media_state);
        seekBar = findViewById(R.id.media_seek_progress);
        seekBar.setOnSeekBarChangeListener(new MySeekBar());

        format = new SimpleDateFormat("mm:ss");
        mediaEntity = (MediaEntity) getIntent().getSerializableExtra("mediaEntity");

        //设置显示的信息
        if (!TextUtils.isEmpty(mediaEntity.getTitle())){
            mediaTitleTv.setText(mediaEntity.getTitle());
        }
//        mediaContext.setText(mediaEntity.getSummary());
        mediaContext.setMovementMethod(ScrollingMovementMethod.getInstance());

        String nameAndtime = "";
        if (!TextUtils.isEmpty(mediaEntity.getDoctorName())){
            nameAndtime = mediaEntity.getDoctorName();
        }

        if (!TextUtils.isEmpty(mediaEntity.getDueTime())){
            nameAndtime = nameAndtime +" "+ mediaEntity.getDueTime();
        }

        mediaTimeTv.setText(nameAndtime);
        if (mediaEntity.getFrequencyUrl()!=null && mediaEntity.getFrequencyUrl().length()>0){
            scrollView.setVisibility(View.VISIBLE);
            mediaNoImg.setVisibility(View.GONE);
        }else{
            scrollView.setVisibility(View.GONE);
            mediaNoImg.setVisibility(View.VISIBLE);
        }

        if (ContextCompat.checkSelfPermission(MediaPlayerActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MediaPlayerActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            initMediaPlayer();//初始化mediaplayer
        }

        //监听播放时回调函数
        timer = new Timer();
        timer.schedule(new TimerTask() {

            Runnable updateUI = new Runnable() {
                @Override
                public void run() {
                    if (mediaPlayer != null) {
                        currentTv.setText(format.format(mediaPlayer.getCurrentPosition()) + "");
                    }
                }
            };

            @Override
            public void run() {
                if (!isSeekBarChanging) {
                    seekBar.setProgress(mediaPlayer.getCurrentPosition());
                    runOnUiThread(updateUI);
                }
            }
        }, 0, 50);
    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {
        mediaStateIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mediaPlayer.isPlaying()) {
                    mediaStateIv.setBackground(getResources().getDrawable(R.mipmap.media_play));
                    mediaPlayer.start();//开始播放
                    mediaPlayer.seekTo(seekBar.getProgress());

                    //监听播放时回调函数
                    timer = new Timer();
                    timer.schedule(new TimerTask() {

                        Runnable updateUI = new Runnable() {
                            @Override
                            public void run() {
                                currentTv.setText(format.format(mediaPlayer.getCurrentPosition()) + "");
                            }
                        };

                        @Override
                        public void run() {
                            if (!isSeekBarChanging) {
                                seekBar.setProgress(mediaPlayer.getCurrentPosition());
                                runOnUiThread(updateUI);
                            }
                        }
                    }, 0, 50);
                } else {
                    mediaStateIv.setBackground(getResources().getDrawable(R.mipmap.media_stop));
                    mediaPlayer.pause();//暂停播放
                }
            }
        });
        //加15s
        mediaAddLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaPlayer.seekTo(seekBar.getProgress() + 15000);
            }
        });
        //减15s
        mediaReduceLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaPlayer.seekTo(seekBar.getProgress() - 15000);
            }
        });
        backIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initMediaPlayer() {
        try {
            mediaPlayer.setDataSource(mediaEntity.getFrequencyUrl());//指定音频文件的路径
            mediaPlayer.prepare();//让mediaplayer进入准备状态
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                public void onPrepared(MediaPlayer mp) {
                    seekBar.setMax(mediaPlayer.getDuration());
                    totalTv.setText(format.format(mediaPlayer.getDuration()) + "");
                    currentTv.setText("00:00");
                }
            });
            // 监听音频播放完的代码，实现音频的自动循环播放
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer arg0) {
                    mediaStateIv.setBackground(getResources().getDrawable(R.mipmap.media_stop));
                }
            });
            mediaPlayer.start();//开始播放
            mediaPlayer.seekTo(0);
            mediaStateIv.setBackground(getResources().getDrawable(R.mipmap.media_play));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 &&
                        grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initMediaPlayer();
                } else {
                    Toast.makeText(MediaPlayerActivity.this, "denied access", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isSeekBarChanging = true;
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    /*进度条处理*/
    public class MySeekBar implements SeekBar.OnSeekBarChangeListener {

        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
        }

        /*滚动时,应当暂停后台定时器*/
        public void onStartTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = true;
        }

        /*滑动结束后，重新设置值*/
        public void onStopTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = false;
            mediaPlayer.seekTo(seekBar.getProgress());
        }
    }
}
